import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Register from '../views/Register.vue'
import request from '../utils/request.js';

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children: [{
      path: '', component: () => import('../views/Index.vue')
    }, {
      path: 'kblist', component: () => import('../views/koubei/Kblist.vue')
    },{
      path: 'kbadd', component: () => import('../views/koubei/Kbadd.vue')
    },{
      path: 'kbedit', component: () => import('../views/koubei/Kbedit.vue')
    }]
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 路由守卫
router.beforeEach((to, from, next) => {
  // to: 要进入的目标路由对象，到哪里去
  // from: 正要离开导航的路由对象， 从哪里来
  // next: 用来决定跳转或取消导航（如果不写这个，就无法进入导航）
  // console.log(to, from);
  if (to.path === '/login' || to.path === '/register') {
    next();
  } else {
    request({
      method: 'post',
      url: '/verifyToken'
    }).then(r => {
      if (r.data.code === 1) {
        console.log('未登录');
        router.push('/login')
      }
      if (r.data.code === 2) {
        console.log(r.data.msg);
        localStorage.removeItem('token')
        router.push('/login')
      }
      if (r.data.code === 0) {
          next();
      }
    })
  }
})

export default router
